package com.han.dao.concrete.product;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import com.han.dao.abstraction.product.GenericDAO;

public abstract class DataAccessObject implements GenericDAO {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5678424095726710140L;
	protected DataSource datasource;
	protected Context context;
	protected Connection connection;
	protected PreparedStatement preparedStatement;
	protected ResultSet resultSet;
	protected static Logger logger = Logger.getLogger(DataAccessObject.class);

	public void connect() throws SQLException, NamingException {
		try {
			context = new InitialContext();
			datasource = (DataSource) context.lookup("java:comp/env/jdbc/beta_test_engine");
			this.connection = datasource.getConnection();
		} catch (SQLException e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			throw e;
		} catch (NamingException e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			throw e;
		}
	}

	public void disconnect() throws SQLException {
		if (this.resultSet != null) {
			try {
				this.resultSet.close();
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
				throw e;
			}
		}

		if (this.preparedStatement != null) {
			try {
				this.preparedStatement.close();
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
				throw e;
			}
		}

		if (this.connection != null) {
			try {
				this.connection.close();
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
				throw e;
			}
		}
	}
}
